$(document).ready(function(){
    /**
     * 该方案中 通过 hide() show() 方法来控制项目的显示隐藏。
     *  */
    var startDate = new Date();
    // 获取当前月
    var curMonth = startDate.getFullYear() + '-' + (startDate.getMonth() + 1);
    console.log('init:', curMonth);
  
    var localStore = {};    //用于本地缓存获取的数据。
    var isTest = true;
    var isListUpdating = false;
    
    init_view();
    
    function is_show_profit() {
        return $("#checkbox_1").is(':checked');
    }

    function is_show_reward() {
        return $("#checkbox_2").is(':checked');
    }

    function is_show_sugar() {
        return $("#checkbox_3").is(':checked');
    }
    
    function produceItem_date(date) {
        return '<div class="date tiem0">'
                +    '<div class="icon"></div>'
                +    '<span class="date">'+ date + '</span>'
                +'</div>';
    }
    
    function produceItem( index, itemData, couponData ) {
        var comData = {
            '1' : {
                'title': '锁仓收益',
                'className': 'item1',
            },
            '2' : {
                'title': '返佣奖励',
                'className': 'item2',
            },
            '3': {
                'title': '糖果',
                'className': 'item3',
            }
        }
        var item_class = comData[index].className;
        var item_title = comData[index].title;
        var item_dark_str = itemData.isDark ? 'dark' : '';
        var icon_show_str = itemData.isShowIcon ? 'show' : '';
        var date_str = itemData.date;       // 2018-12-11;
        var tsr_num = itemData.count;       //500;
        var coupon_div = '';
        if (couponData) {
            var coupon_str = couponData.count > 0 ? 'coupon' : '';
            coupon_div = '<div class="detail-2 ' + coupon_str + '">+<span>' + couponData.count + '</span>优惠券</div>';
        }
        return '<div class="item container ' + item_class + ' ' + item_dark_str +'">'
                +    '<div class="des des-title">' + item_title + '</div>'
                +    '<div class="des des-date">' + date_str + '</div>'
                +    '<div class="des des-detail">'
                +        '<div class="detail-1">+<span>' + tsr_num + '</span>TSR</div>'
                +        coupon_div
                +   ' </div>'
                +   '<div class=" ' + icon_show_str + '"></div>'
                + '</div>';
    }
    
    // 根据数据生成 显示项
    function produceListItem(number) {
        
        var date_str_1 = number.day;    // '11月21日';
        var date_str_2 = number.time;   //  '2018-11-21';
        
        var data_profit = {}; 
        data_profit.isDark = false; 
        data_profit.isShowIcon = false; 
        data_profit.date = date_str_2; 
        data_profit.count = number.static_amount === undefined ? 0 : + number.static_amount;    // 500;
        
        var data_reward = {}; 
        data_reward.isDark = false; 
        data_reward.isShowIcon = false; 
        data_reward.date = date_str_2; 
        data_reward.count = number.commission_amount === undefined ? 0 : number.commission_amount;
        
        var data_sugar = {}; 
        data_sugar.isDark = !(number.static_status == 1); 
        data_sugar.isShowIcon = !(number.static_status == 1); 
        data_sugar.date = date_str_2;
         data_sugar.count = number.directly_amount === undefined ? 0 : number.directly_amount;
        var data_coupon = {}; 
        data_coupon.count = number.coupon_amount === undefined ? 0 : number.coupon_amount;
        
        /***************************************************************************************/
        
        var text_0 = produceItem_date(date_str_1);
        
        var text_1 = produceItem(1, data_profit,);
        var text_2 = produceItem(2, data_reward, data_coupon);
        var text_3 = produceItem(3, data_sugar);
        
        var total_tsr = data_profit.count +  data_reward.count + data_sugar.count;
        var total_coupon = data_coupon.count;
        var text_4 = produceItem_total(total_tsr, total_coupon);
        
        var li_str = '<li class="list-item item-container">' + text_0 + text_1 + text_2 + text_3 + text_4 + '</li>';
        
        return li_str;
    }

    function produceItem_total(total_tsr, total_coupon) {
        return '<div class="item-total item4 container-end">'
                + '<div class="tsr">+<span class="total-tsr">'+ total_tsr + '</span>TSR</div>'
                + '<div class="blank"></div>'
                + '<div class="coupon"><span class="total-coupon">'+ total_coupon + '</span>优惠券'
                + '</div>';
    }

    function setBtnDate( selectedMonth ) {
        var text = '';
        if ( selectedMonth ) {
            text = selectedMonth.split('-')[0] + '年' + selectedMonth.split('-')[1] + '月';
        } else {
            // 设置为当前时间
            text = startDate.getFullYear() + '年' + (startDate.getMonth() + 1) + '月';
        }
        
        $('#my-date span').html(text);
    }
    
    function refreshTotal() {
        // 更新总TSR
        $('.total-tsr').each(function () {
            var total_tsr = 0;
            $(this).parent().parent().siblings().filter(function() {
                if ($(this).is(":visible")) {
                    total_tsr += (+$(this).find('.detail-1 span').text());
                }
            });
            
            $(this).text(total_tsr);
        });
        // 更新总优惠券
        $('span.total-coupon').each(function () {
            var total_coupon = 0;
            if ($(this).parent().parent().siblings('.item2').is(':visible')) {
                total_coupon += (+$(this).parent().parent().siblings('.item2').find('.detail-2 span').text());
            }
            
            $(this).text(total_coupon);
        })
    }
    
    // 显示 隐藏对应项
    function refreshItemShowByOptions() {
        if (is_show_profit()) {
            $(".item1").show();
        } else {
            $(".item1").hide();
        }
        if (is_show_reward()) {
            $(".item2").show();
        } else {
            $(".item2").hide();
        }
        if (is_show_sugar()) {
            $(".item3").show();
        } else {
            $(".item3").hide();
        }
        
        // 如果3个都隐藏，则<li></li> 标签添加隐藏。
        if (!is_show_profit() && !is_show_reward() && !is_show_sugar()) {
            $('li').hide();
        } else {
            $('li').show();
        }
    }
    
    // 选项按钮 样式更新。
    function refreshOptions() {
        if (is_show_profit()) {
            $(".option1").addClass('option-color');
        } else {
            $(".option1").removeClass('option-color');
        }
        if (is_show_reward()) {
            $(".option2").addClass('option-color');
        } else {
            $(".option2").removeClass('option-color');
        }
        if (is_show_sugar()) {
            $(".option3").addClass('option-color');
        } else {
            $(".option3").removeClass('option-color');
        }
        
        refreshItemShowByOptions();
        refreshTotal();
    }

    function updateBonusList( monthData ) {
        console.log('origin: ', monthData);
        if (!monthData || Object.keys(monthData).length === 0) {
            monthData = localStore[curMonth];
            console.log(localStore[curMonth]);
        }
        
        $('#op-static').text((monthData.price_static == undefined ? 0 : monthData.price_static ) + 'TSR');
        $('#op-commission').text((monthData.price_commission == undefined ? 0 : monthData.price_commission ) + 'TSR');
        $('#op-directly').text((monthData.price_directly == undefined ? 0 : monthData.price_directly) + 'TSR');
        
        $('#list-content ul').empty();
        var len = monthData.list.length;
        if (len <= 0) {
            $('#list-content ul').text('没有本月的数据！');
        }        
        
        for (var i = 0; i < len; i++ ) {
            // var data = monthData[i];
            var number = monthData.list[i];
            $('#list-content ul').append(produceListItem(number));
        }
        
        isListUpdating = false;
    }
    
    function init_view() {
        // $("#checkbox_1").prop("checked",true);
        // $("#checkbox_2").prop("checked",true);
        // $("#checkbox_3").prop("checked",true);
        
        setBtnDate( curMonth );
        
        refreshOptions();
        
        getData(curMonth, function(data) {
            updateBonusList( data );
        });
    }
    
    function getUrl(year, month) {
        // return baseUrl + '/api/member/get-bonus?year='+ year +'&month='+ month +'&access-token='+ token +'&types=3,4,5,6';
        return 'http://www.dengwenhao.com:727/api/member/get-bonus?year='+ year +'&month='+ month +'&access-token=TAICNrPewvEVWaRHbasvFGOG8Ba9Fq3Y92X6Szo8T3';
    }
    
    // 请求数据， monthStr: '2018-12'
    function getData( monthStr, cb ) {
        console.log('请求数据...');
        isListUpdating = true;
        var year = monthStr.split('-')[0];
        var month = monthStr.split('-')[1];
        var url = getUrl(year, month);
        try {
            $.get(url, function(data, status) {
                if (data.errcode == 0 && status == 'success') {
                    var monthData = data.data;
                    localStore[monthStr] = monthData;
                    if (typeof cb == 'function') {
                        cb(monthData);
                    } else {
                        console.log(cb + ' is not a callback function!');
                    }
                } else {
                    console.error('Get data failed: ' + curMonth);
                    cb( {} );
                    throw Error('获取数据失败！');
                }
                
                /***************************************************************************************/
            });
        } catch (error) {
            console.error(error);
            isListUpdating = false;
        }
    }
    
    
    
    $('.btn-back').on('click', function() {
        console.log('back button');
    })
    
    // 锁仓收益按钮
    $('#selection').on('click','.option1',function(ev) {
        if (isListUpdating) {
            console.log('列表加载中');
            return;
        }
        if (ev.target.id !== 'checkbox_1') {
            if (is_show_profit()) {
                $("#checkbox_1").prop("checked",false);
            } else {
                $("#checkbox_1").prop("checked",true);
            }
        }
        
        console.log('option1');
        refreshOptions();
    })
    
    // 返佣奖励 按钮
    $('#selection').on('click','.option2',function(ev) {
        if (isListUpdating) {
            console.log('列表加载中');
            return;
        }
        if (ev.target.id !== 'checkbox_2') {
            if (is_show_reward()) {
                $("#checkbox_2").prop("checked",false);
            } else {
                $("#checkbox_2").prop("checked",true);
            }
        }
        
        console.log('option2');
        refreshOptions();
    })

    // 糖果按钮
    $('#selection').on('click','.option3', function(ev) {
        if (isListUpdating) {
            console.log('列表加载中');
            return;
        }
        if (ev.target.id !== 'checkbox_3') {
            if (is_show_sugar()) {
                $("#checkbox_3").prop("checked",false);
            } else {
                $("#checkbox_3").prop("checked",true);
            }
        }
        
        console.log('option3');
        refreshOptions();
    })

    // $('.btn-time-select').on('click', function(ev) {
    //     console.log('show date picker');
    // })
    var calendar = new datePicker();
    calendar.init({
        'trigger': '#my-date',  /*按钮选择器，用于触发弹出插件*/
        'type': 'ym',         /*模式：date日期；datetime日期时间；time时间；ym年月；*/
        'minDate':'2010-1-1',   /*最小日期*/
        'maxDate':'2100-12-31', /*最大日期*/
        'onSubmit':function(){  /*确认时触发事件*/
            // var theSelectData = calendar.value;
            console.log('selected:', calendar.value);
            if (curMonth == calendar.value) {
                console.log('时间没有变化，不做处理！');
                return;
            }
            
            var nowDate = new Date();
            var selectDate = new Date(calendar.value);
            if (selectDate.getTime() <= nowDate.getTime()) {
                curMonth = calendar.value;
            } else {
                curMonth = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1);
                console.log('选择的时间段超出，默认显示当前月的数据。 ' + curMonth + '  : 2');
            }
            setBtnDate( curMonth );
            
            if (localStore[curMonth]) {     // 如果本地缓存有当前月的数据。
                console.log('取本地数据');
                updateBonusList(localStore[curMonth]);
            } else {                        // 否则，重新请求数据。
                console.log('重新请求数据...');
                getData(curMonth, function(data) {
                    updateBonusList(data);
                });
            }
        },
        'onClose':function(){/*取消时触发事件*/
        }
    });
});